#!/usr/bin/python

import socket
import select

HOST = ''                 # Symbolic name meaning the local host
PORT = 1337              # Arbitrary non-privileged port
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(20)

socketlist = [server]

class FluzzyBunny:
	score = 0
	position = (0, 0)
	velocity = (0, 0)
	name = "Dott"
	socket = 0
	def __init__ (self, name, socket):
		self.name = name
		self.socket = socket
	
rabbits = []

while 1: # Is it Wednesday yet?
		
	read, write, error = select.select(socketlist, socketlist, [], 0)

	if server in read:
		conn, addr = server.accept()
		print "Bunny connected to server from", conn.getpeername(), "."
		socketlist.append(conn)
		read.remove(server)

	for s in read:
		# We's gots datas.
		data = s.recv(1024)

		# If there are more sockets than connections, we need to add a new connection.
		if len(rabbits) != len(socketlist)-1:
			flag = 0
			# Check that we are recieving from the correct socket.
			for r in rabbits:
				if r.socket == s:
					flag = 1
					break
			# If yes, we add a new connection to the list.
			if flag == 0:
				rabbits.append(FluzzyBunny(repr(data), s))

	# Send outputs to clients.
	for s in write:
		if s != server:
			try:
				#s.send("run wabbit run")
				pass
			except socket.error, msg:
				socketlist.remove(s)
				continue



# Client->Server messages:
# bunny_id: byte (Lower 5 Bits)
# button_states: byte (Upper 3 Bits)
# Total: 1 Byte
# Only needs to be sent when state changes.
#
# Server->Client messages:
# bunny_id: byte (Lower 3 bits)
# animation:  byte (Upper 5 bits)
# bunny_x:  short int (2 bytes)
# bunny_y:  short int (2 Bytes)
# Total: 5 Bytes
# Needs to be sent when that bunny changes position.

